package org.geektimes.include;


import org.geektimes.injection.component.ComponentBean;
import org.geektimes.injection.context.ComponentContext;
import org.geektimes.injection.context.Initializer.IncludeComponentInitializer;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Objects;

/**
 * @FileName: ValidatorComponentInitializer
 * @Description: validator初始化器
 * @Author: MaWenHao
 * @Created: 2021/3/10 - 下午9:13
 */
public class ValidatorComponentInitializer implements IncludeComponentInitializer {

    private ValidatorFactory validatorFactory;

    private Validator validator;

    /**
     * 初始化方法,将第三方组件注册到容器上下文对象中
     *
     * @param componentContext
     */
    @Override
    public void init(ComponentContext componentContext) {
        validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
        componentContext.putComponent(Validator.class.getSimpleName(), new ComponentBean(validator));
        componentContext.putComponent(ValidatorFactory.class.getSimpleName(), new ComponentBean(validatorFactory));
    }

    /**
     * 组件 销毁方法
     *
     * @param componentContext
     */
    @Override
    public void destroy(ComponentContext componentContext) {
        if (Objects.nonNull(validatorFactory)) {
            validatorFactory.close();
        }
    }
}
